package com.example.demo.controller;

import com.example.demo.entity.TestRecord;
import com.example.demo.repository.TestRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/test-records")
@CrossOrigin
public class TestRecordController {

    @Autowired
    private TestRecordRepository testRecordRepository;

    // 获取所有测试记录
    @GetMapping
    public List<TestRecord> getAllTestRecords() {
        return testRecordRepository.findAll();
    }

    // 根据ID获取单条测试记录
    @GetMapping("/{id}")
    public ResponseEntity<TestRecord> getTestRecordById(@PathVariable Long id) {
        return testRecordRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // 根据学生ID获取该学生所有测试记录
    @GetMapping("/student/{studentId}")
    public List<TestRecord> getTestRecordsByStudentId(@PathVariable Long studentId) {
        return testRecordRepository.findByStudentId(studentId);
    }

    // 新增测试记录
    @PostMapping
    public TestRecord createTestRecord(@RequestBody TestRecord testRecord) {
        return testRecordRepository.save(testRecord);
    }

    // 更新测试记录
    @PutMapping("/{id}")
    public ResponseEntity<TestRecord> updateTestRecord(@PathVariable Long id, @RequestBody TestRecord testRecord) {
        return testRecordRepository.findById(id).map(existing -> {
            existing.setStudentId(testRecord.getStudentId());
            existing.setTestTime(testRecord.getTestTime());
            existing.setResult(testRecord.getResult());
            existing.setResultType(testRecord.getResultType());
            testRecordRepository.save(existing);
            return ResponseEntity.ok(existing);
        }).orElse(ResponseEntity.notFound().build());
    }

    // 删除测试记录
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTestRecord(@PathVariable Long id) {
        if (!testRecordRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        testRecordRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}
